<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用鼠标改变 attribute 变量的值</title>
</head>
<body>

<canvas id="webgl" width="400" height="400"></canvas>

<script>
(function(){
    var canvas = document.getElementById('webgl');
    var gl = canvas.getContext('webgl');

    // shader source
    var VSHADER_SOURCE =
        `attribute vec4 a_Position;
        void main() {
            gl_Position = a_Position;
            gl_PointSize = 10.0;
        }`;
    var FSHADER_SOURCE =
        `void main() {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }`;

    // 创建 shader
    var vShader = gl.createShader(gl.VERTEX_SHADER);
    // 设置 shader 的 source
    gl.shaderSource(vShader, VSHADER_SOURCE);
    // 编译 shader
    gl.compileShader(vShader);

    var fShader = gl.createShader(gl.FRAGMENT_SHADER);
    gl.shaderSource(fShader, FSHADER_SOURCE);
    gl.compileShader(fShader);

    // 创建程序 并附加 shader
    var program = gl.createProgram();
    gl.attachShader(program, vShader);
    gl.attachShader(program, fShader);
    // 连接程序到 webgl
    gl.linkProgram(program);

    gl.useProgram(program);
    gl.program = program;

    // 通过鼠标点击给 attribute 赋值
    var a_Position = gl.getAttribLocation(gl.program, 'a_Position');

    /*
    [
        x0, y0
        x1, y1
        x2, y2
        ...
    ]
    */
    var clickPoints = [];
    canvas.onclick = (e) => {
        var x = e.clientX;
        var y = e.clientY;
        var rect = e.target.getBoundingClientRect();

        // canvas 坐标转换到 webgl 坐标
        x = x - rect.left - canvas.width / 2;
        y = canvas.height / 2 - (y - rect.top);

        // webgl 坐标从 -1 到 1
        x = x / (canvas.width / 2);
        y = y / (canvas.height / 2);

        clickPoints.push(x);
        clickPoints.push(y);

        gl.clear(gl.COLOR_BUFFER_BIT);

        // 绘制
        for(var i=0; i<clickPoints.length; i+=2) {
            gl.vertexAttrib3f(a_Position, clickPoints[i], clickPoints[i+1], 0);
            gl.drawArrays(gl.POINTS, 0, 1);
        }
    };

    // 指定清空 canvas 的颜色
    gl.clearColor(0, 0.2, 0, 1.0);
    // 清空 canvas
    gl.clear(gl.COLOR_BUFFER_BIT);

})();
</script>
</body>
</html>
